const OpenAI = require('openai')
const Router = require('koa-router')
const router = new Router()
const axios = require('axios');

const openai = new OpenAI(
    {
        // 若没有配置环境变量，请用百炼API Key将下行替换为：apiKey: "sk-xxx",
        apiKey: 'sk-2306c28e001a4397af9bffb951fe179d',
        baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1"
    }
);

// 优化空格换行处理的中间件
router.post('/openai/chat', async (ctx) => {
    // console.log(ctx.request.body)
    const message = ctx.request.body.content // 前端传过来的消息

    let reasoningContent = '';
    let answerContent = '';
    let isAnswering = false;

    // 启动流式响应
    ctx.set('Content-Type', 'text/plain; charset=utf-8');
    ctx.res.writeHead(200, {
        'Transfer-Encoding': 'chunked', // 指定流式传输
    });

    try {
        const stream = await openai.chat.completions.create({
            model: 'deepseek-r1',
            messages: [{ role: 'user', content: message }],
            stream: true
        });

        console.log('\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\nUsage:');
                console.log(chunk.usage);
                continue;
            }

            const delta = chunk.choices[0].delta;
            
            // 处理思考过程
            if (delta.reasoning_content) {
                process.stdout.write(delta.reasoning_content);
                reasoningContent += delta.reasoning_content;
            } 
            // 处理正式回复
            else if (delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
                ctx.res.write(delta.content)
            }
        }
    } catch (error) {
        console.error('Error:', error);
        ctx.body = {
            code: 500,
            message: '请求失败，请稍后重试'
        };
    }

})

module.exports = {
    questionRouter: router
}